package client_core

import (
	"context"
	"github.com/chicken-team-outside/chicken_transmission/client_core/config"
	_ "github.com/chicken-team-outside/chicken_transmission/logger"
	"github.com/gin-gonic/gin"
	"go.uber.org/zap"
)

type BaseResponse struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data"`
}

func initApi(ctx context.Context, engine *gin.Engine) {
	api := engine.Group("/api")
	api.POST("/log_level", setLogLevel)
	api.GET("/log_level", getLogLevel)
	api.POST("/http_config", setHttpConfig)
	api.GET("/http_config", getHttpConfig)
	initFsApi(api.Group("/fs"))
	initLocalDriver(api.Group("/local"))
	initNetDisk(api.Group("/net_disk"))
	initLocalFileApi(api.Group("/local_file"))
	initTaskApi(ctx, api.Group("/task"))
	initNotifyMgr(ctx, api.Group("/socket-io-api"))
}

func Success(ctx *gin.Context, data interface{}, msg string) {
	ctx.JSONP(200, &BaseResponse{
		Code: 200,
		Data: data,
		Msg:  msg,
	})
}

func BadParameter(ctx *gin.Context) {
	ctx.JSONP(200, &BaseResponse{
		Code: 400,
		Msg:  "参数错误",
	})
}

func BadRequest(ctx *gin.Context, msg string) {
	ctx.JSONP(200, &BaseResponse{
		Code: 400,
		Msg:  msg,
	})
}

func setLogLevel(ctx *gin.Context) {
	var logLevel string
	err := ctx.BindJSON(&logLevel)
	if err != nil {
		zap.L().Warn("error to bind json", zap.Error(err))
		BadRequest(ctx, "参数错误")
		return
	}
	err = config.SaveLogLevel(logLevel)
	if err != nil {
		zap.L().Error("Error saving log level", zap.Error(err))
		BadRequest(ctx, "设置失败")
	} else {
		Success(ctx, nil, "成功")
	}
}

func getLogLevel(ctx *gin.Context) {
	Success(ctx, config.LogLevel(), "成功")
}

func setHttpConfig(ctx *gin.Context) {
	cfg := &config.HttpClientSetting{}
	err := ctx.BindJSON(cfg)
	if err != nil {
		zap.L().Error("Error binding http config", zap.Error(err))
		BadRequest(ctx, "参数错误")
		return
	}
	err = config.SaveHttpConfig(cfg)
	if err != nil {
		zap.L().Error("Error saving http config", zap.Error(err))
		BadRequest(ctx, "设置失败")
		return
	}
	Success(ctx, nil, "设置成功")
}

func getHttpConfig(ctx *gin.Context) {
	Success(ctx, config.HttpClientConfig(), "成功")
}
